package controller.menu;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.DBException;
import model.InputCheck;
import model.InputException;
import model.SessionCheck;

@WebServlet("/Menu")
public class Menu extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected String disp = "/Menu.jsp";
	protected String err_msg = "";
	protected String fullname = "";

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String input_login = request.getParameter("employee_no");
		String input_pass = request.getParameter("password");

		// 入力された値をチェック
		InputCheck inputcheck = new InputCheck(input_login, input_pass);
		try {
			inputcheck.check_null_login();
			fullname = inputcheck.check_password();
		} catch (InputException e) {
			switch (e.getErrorCode()) {
			case InputException.INVALID_INPUT:
				disp = "/InputErr.jsp";
				break;
			case InputException.BLANK_ID:
				disp = "/InputErr.jsp";
				break;
			case InputException.DUPLICATE_ID:
				disp = "/ErrSameEmployeeNo.jsp";
				break;
			}
			// エラーメッセージを設定(入力エラー)
			err_msg += e.getMessage();
			System.out.println(err_msg);

			// エラーコード によって画面変える(DBエラー)
		} catch (DBException e) {
			disp = "/DBErr.jsp";

			// エラーメッセージを設定(DBエラー)
			err_msg += e.getMessage();
			System.out.println(err_msg);
		}

		// セッションを作成
		SessionCheck sessioncheck = new SessionCheck(request);
		sessioncheck.createsession();
		// セッションにユーザ情報を格納
		sessioncheck.inputuserinfo(fullname);

		// 画面を表示する
		request.setCharacterEncoding("UTF-8");
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(disp);
		rd.forward(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// セッションのチェック
		SessionCheck sessioncheck = new SessionCheck(request);
		disp = sessioncheck.checksession(disp);

		// 画面遷移する
		request.setCharacterEncoding("UTF-8");
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(disp);
		rd.forward(request, response);
	}
}
